package com.colabo.j2ee.web.oaf.security.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.colabo.j2ee.web.core.context.CoreInitInfo;

/**
 * web.xml中注册的用于代理spring security过滤链对象
 * 此处增加配置，用于是否启动安全控制机制
 * @author Anthony
 *
 */
public class SecurityFilterProxy implements Filter {
	// Static Fields ============================================
	
	private static final String SPRING_SECURITY_FILTER = "org.springframework.web.filter.DelegatingFilterProxy";
	
	// Instance Fields ============================================
	private Log logger = LogFactory.getLog(SecurityFilterProxy.class);
	private Filter securityFilter;

	public void destroy() {
		if (securityFilter == null) {
			return;
		}
		securityFilter.destroy();
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
			ServletException {
		if (logger.isDebugEnabled()) {
			logger.debug("****进入安全控制代理过滤器****");
		}
		if (securityFilter == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("****未启用Spring Security安全控制框架****");
			}
			chain.doFilter(req, resp);
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("****启用Spring Security安全控制框架****");
			}
			securityFilter.doFilter(req, resp, chain);
		}
	}

	public void init(FilterConfig config) throws ServletException {
		if (!CoreInitInfo.getInstance().getBooleanProp("springsecurity.enabled")) {
			if (logger.isDebugEnabled()) {
				logger.debug("****系统配置：Spring Security安全框架未启用****");
			}
			return;
		}
		try {
			if (logger.isDebugEnabled()) {
				logger.debug("****初始化Spring Security安全框架****");
			}
			securityFilter = (Filter) Class.forName(SPRING_SECURITY_FILTER).newInstance();
			securityFilter.init(config);
		} catch (InstantiationException e) {
			logger.error("初始化Spring Security安全控制过滤器失败，class: " + SPRING_SECURITY_FILTER, e);
		} catch (IllegalAccessException e) {
			logger.error("构造函数访问异常，class: " + SPRING_SECURITY_FILTER, e);
		} catch (ClassNotFoundException e) {
			logger.error("未找到设定的Spring Security过滤器，class: " + SPRING_SECURITY_FILTER, e);
		} catch (Exception e) {
			logger.error("发生未知异常", e);
		}
	}
}
